package com.springdemo.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

// 时间打印任务
public class TimePrintTask implements Runnable {
    private final String taskName;
    private final int durationSeconds; // 任务持续时间(秒)

    public TimePrintTask(String taskName, int durationSeconds) {
        this.taskName = taskName;
        this.durationSeconds = durationSeconds;
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("任务 [" + taskName + "] 开始执行，线程名: " + Thread.currentThread().getName());

        try {
            // 执行指定秒数的任务，每秒输出一次时间
            for (int i = 0; i < durationSeconds; i++) {
                String currentTime = sdf.format(new Date());
                System.out.println("任务 [" + taskName + "] " + (i + 1) + "秒: " + currentTime);
                TimeUnit.SECONDS.sleep(1); // 休眠1秒
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("任务 [" + taskName + "] 被中断");
        }

        System.out.println("任务 [" + taskName + "] 执行完成");
    }
}
